package com.flx.sys.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.flx.sys.jwt.dto.JwtAuthenticationRequest;
import com.flx.sys.jwt.dto.JwtAuthenticationResponse;
import com.flx.sys.service.AuthSerevice;

/**
 * token
 * @author zm
 * 2018年4月19日
 */
@RestController
public class AuthController {

	@Value("${jwt.header}")
	private String tokenHeader;

	@Autowired
	private AuthSerevice authSerevice;
	
	@Autowired
	private PasswordEncoder passwordEncoder;

	/**获取token
	 * @param request
	 * @return
	 * 2018年4月20日
	 */
	@PostMapping(value = "${jwt.authentication.create.token.path}")
	public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtAuthenticationRequest request) {
		final String token = authSerevice.login(request.getUsername(), request.getPassword());
		return ResponseEntity.ok(token);
	}
	@GetMapping(value = "${jwt.authentication.refres.token.path}")
	public ResponseEntity<?> refreshAndGenAuthenticationToken(HttpServletRequest request){
		String token = request.getHeader(tokenHeader);
		
		String refreshedToken = authSerevice.refresh(token);
		if(refreshedToken == null){
			return ResponseEntity.badRequest().body(null);
		}else{
			return ResponseEntity.ok(new JwtAuthenticationResponse(refreshedToken));
		}
		
	}

}
